<?php

namespace App\Orchid\Layouts\Post;

use App\Models\Post;
use Orchid\Screen\TD;
use Orchid\Screen\Actions\Link;
use Orchid\Screen\Actions\Button;
use Orchid\Screen\Layouts\Table;

class PostListLayout extends Table
{
    protected $target = 'posts';

    protected function columns(): array
    {
        return [
            TD::make('cover_image_id', '封面图')
                ->render(function (Post $post) {
                    return $post->coverImage
                        ? '<img src="'.$post->coverImage->url.'" width="100" height="100" alt="封面图">' 
                        : '无封面图';
                }),
                
            TD::make('title', '标题')
                ->sort()
                ->filter(TD::FILTER_TEXT)
                ->render(function (Post $post) {
                    return Link::make($post->title)
                        ->route('platform.posts.edit', $post);
                }),
                
            TD::make('category.name', '分类')
                ->sort()
                ->render(function (Post $post) {
                    return $post->category ? $post->category->name : '-';
                }),
                
            TD::make('user.name', '作者')
                ->render(function (Post $post) {
                    return $post->user ? $post->user->name : '-';
                }),
            
            TD::make('status', '状态')
                ->render(function (Post $post) {
                    return match($post->status ?? 'draft') {
                        'published' => '<span class="text-success">已发布</span>',
                        'draft' => '<span class="text-warning">草稿</span>',
                        'archived' => '<span class="text-muted">已归档</span>',
                        default => $post->status,
                    };
                }),
                
            TD::make('published_at', '发布日期')
                ->sort()
                ->render(function (Post $post) {
                    return $post->published_at ? $post->published_at->format('Y-m-d') : '-';
                }),
                
            TD::make('操作')
                ->align(TD::ALIGN_CENTER)
                ->width('100px')
                ->render(function (Post $post) {
                    return Button::make('删除')
                        ->icon('trash')
                        ->confirm('确定要删除这篇文章吗？')
                        ->method('remove', ['post' => $post->id]);
                }),
        ];
    }
}